<template>
  <el-row>
    <div class="catalogue-menu">
      <div class="catalogue-button-wrap">
        <el-button :class="activeMenu==='1'?' catalogue-button-hover catalogue-button' :'catalogue-button'"
                   @click="changeMenu('1')">
          <el-icon class="button-icon">
            <TechShareIconHover v-if="activeMenu==='1'"/>
            <TechShareIcon v-else/>
          </el-icon>
          <div class="button-font">
            专业知识
          </div>
        </el-button>
        <el-button :class="activeMenu==='2'?' catalogue-button-hover catalogue-button' :'catalogue-button'"
                   @click="changeMenu('2')">
          <el-icon class="button-icon">
            <QuestionStoreHover v-if="activeMenu==='2'"/>
            <QuestionStore v-else/>
          </el-icon>
          <div class="button-font">问题案例</div>
        </el-button>
        <el-button :class="activeMenu==='4'?' catalogue-button-hover catalogue-button' :'catalogue-button'"
                   @click="changeMenu('4')">
          <el-icon class="button-icon">
            <AfterSalesHover v-if="activeMenu==='4'"/>
            <AfterSales v-else/>
          </el-icon>
          <div class="button-font">市场售后</div>
        </el-button>
        <el-button :class="activeMenu==='3'?' catalogue-button-hover catalogue-button' :'catalogue-button'"
                   @click="changeMenu('3')">
          <el-icon class="button-icon">
            <OtherIconHover v-if="activeMenu==='3'"/>
            <OtherIcon v-else/>
          </el-icon>
          <div class="button-font">其他分享</div>
        </el-button>
      </div>
    </div>
    <div class="collapse-content">
      <el-tree class="catalogue-tree"
               :draggable="dragFlag"
               :default-expanded-keys="expandedKeys"
               node-key="id"
               :data="catalogueList"
               :props="defaultProps"
               @node-drag-start="dragStart"
               @node-drag-end="dragEnd"
               @node-drag-over="handleDragMove"
               @node-drop="dragDrop"
               @node-expand="handleNodeExpand"
               @node-collapse="handleNodeCollapse"
      >
        <template #default="{data}">
          <div class="file">
            <div class="enter-button" @click="enterPreview(data.documentId,data.type)">
              &nbsp;
            </div>
            <OneFileOrDir v-model:dragFlag="dragFlag" :document="data"/>
          </div>
        </template>
      </el-tree>
    </div>
  </el-row>
</template>
<script setup>
import {onBeforeUnmount, onMounted, ref, toRaw, watch} from 'vue';
import QuestionStore from '@/components/common/QuestionStore';
import QuestionStoreHover from '@/components/common/QuestionStoreHover';
import TechShareIcon from '@/components/common/TechShareIcon';
import TechShareIconHover from '@/components/common/TechShareIconHover';
import OtherIcon from '@/components/common/OtherIcon';
import OtherIconHover from '@/components/common/OtherIconHover';
import OneFileOrDir from '@/components/homeShareSpace/OneFileOrDir.vue';
import router from '@/router/index';
import {ElMessage} from "element-plus";
import eventBus from '@/utils/event_bus';
import FrontApi from '@/api/front';
import useCatalogueStore from "@/store/modules/catalogue";
import AfterSales from '@/components/common/AfterSales';
import AfterSalesHover from '@/components/common/AfterSalesHover';

const props = defineProps({
  activeName: Array,
  catalogueType: String
})

const emit = defineEmits(['update:activeName', 'update:catalogueType'])

const store = useCatalogueStore()

const catalogueList = ref([])
const loading = ref(true)
const activeNames = ref(props.activeName)
// const catalogueTree = reactive([])
const activeMenu = ref("1")
const directoryType = ref([])
const expandedKeys = ref([])

const defaultProps = ref({
  children: "children",
  label: "name",
})

const dragFlag = ref(true)
// 树节点展开事件
const handleNodeExpand = (node) => {
  let flag = false
  expandedKeys.value.some(item => {
    if (item === node.id) {
      flag = true
      return true
    }
  })
  if (!flag) {
    expandedKeys.value.push(node.id)
  }
}

// 树节点关闭事件
const handleNodeCollapse = (node) => {
  expandedKeys.value.some((item, index) => {
    if (item === node.id) {
      expandedKeys.value.splice(index, 1)
      return true
    }
  })
  removeChildrenIds(node)

}

const removeChildrenIds = (data) => {
  if (data.children) {
    data.children.forEach(function (item) {
      const index = expandedKeys.value.indexOf(item.id)
      if (index > 0) {
        expandedKeys.value.splice(index, 1)
      }
      removeChildrenIds(item)
    })
  }
}

watch(() => props.activeName, (newVal) => {
  let activeArray = toRaw(newVal)
  activeNames.value = newVal
  if (activeArray.length !== 0) {
    let idPrefix = ''
    if (activeArray.length > 1) {
      idPrefix = activeArray[0]
    }
    setTimeout(() => {
      let idSuffix = activeArray[activeArray.length - 1]
      let el = document.getElementById(idPrefix + '_' + idSuffix)
      el.scrollIntoView({
        block: "center",
        behavior: 'smooth'
      })
    }, 1000)
  }
}, {deep: true})

const getDirectoryType = () => {
  directoryType.value.length = 0
  FrontApi.getDirectoryType().then(res => {
    res.data.forEach(e => {
      const t = {
        "text": e.dictLabel,
        "value": e.dictValue
      }
      directoryType.value.push(t);
    })
  })
}

watch(() => props.catalogueType, (newVal) => {
  loading.value = true
  activeMenu.value = newVal + ''
  store.getCatalogue(String(newVal)).then(res => {
    loading.value = false
    catalogueList.value = res

  }).catch(err => {
    ElMessage(err)
  })
})

// 开始拖拽
const dragStart = () => {

}
// 正在拖拽
const handleDragMove = () => {

}

//拖拽结束
const dragEnd = async (node1, node2, position) => {
  dragFlag.value = false
  let id = node1.data.id
  let oldNum = node1.data.orderNum
  let newNum = node2.data.orderNum
  let oldParentId = node1.data.parentId
  let newParentId = node2.data.parentId
  if (position === "after" && oldParentId === newParentId && oldNum > newNum) {
    let list = node2.parent.data
    if (list.children) {
      list = list.children
    }
    list.forEach((e, i) => {
      if (e.id === node2.data.id) {
        newNum = list[i].orderNum + 1
        newParentId = list[i].parentId
      }
    })
  }

  if (position === "after" && oldParentId !== newParentId) {
    let list = node2.parent.data
    if (list.children) {
      list = list.children
    }
    list.forEach((e, i) => {
      if (e.id === node2.data.id) {
        newNum = list[i].orderNum + 1
        newParentId = list[i].parentId
      }
    })
  }


  if (position === "before" && oldParentId === newParentId && oldNum < newNum) {
    let list = node2.parent.data
    if (list.children) {
      list = list.children
    }
    list.forEach((e, i) => {
      if (e.id === node2.data.id) {
        newNum = list[i].orderNum - 1
        newParentId = list[i].parentId
      }
    })
  }
  let res
  if (newNum !== oldNum || oldParentId !== newParentId) {
    try {
      if (position !== "inner") {
        res = await FrontApi.moveDirectoryChangeOrderNum(id, oldNum, newNum, oldParentId, newParentId, position);
      } else if (position === "inner") {
        res = await FrontApi.moveDirectoryChangeOrderNum(id, oldNum, newNum, oldParentId, node2.data.id, position);
      }
      if (res.data === 1) {
        ElMessage({
          message: '移动成功',
          type: 'success',
        })
      } else {
        ElMessage({
          message: '移动失败',
          type: 'error',
        })
      }
      dragFlag.value = true
      store.updateCatalogue(String(node1.data.type)).then(res => {
        catalogueList.value = res
      }).catch(err => {
        dragFlag.value = true
        ElMessage(err)
      })
    } catch (err) {
      store.updateCatalogue(String(node1.data.type)).then(res => {
        catalogueList.value = res
      }).catch(err => {
        dragFlag.value = true
        ElMessage(err)
      })
    }

  } else {
    store.updateCatalogue(String(node1.data.type)).then(res => {
      catalogueList.value = res
    }).catch(err => {
      dragFlag.value = true
      ElMessage(err)
    })
  }
  dragFlag.value = true
}

const dragDrop = () => {
}

const changeMenu = (type) => {
  activeMenu.value = type + '';
  emit('update:catalogueType', type)
  loading.value = true
  store.getCatalogue(type).then(res => {
    loading.value = false
    catalogueList.value = res
  }).catch(err => {
    ElMessage(err)
  })
}


eventBus.on("updateCatalogueBus", (type) => {
  store.updateCatalogue(type).then(res => {
    loading.value = false
    catalogueList.value = res
    activeMenu.value = type + ''
  }).catch(err => {
    ElMessage(err)
  })
})

eventBus.on("moveDirectoryBus", (obj) => {
  store.updateCatalogue(obj.originType).then(() => {
    loading.value = false
  }).catch(err => {
    ElMessage(err)
  })
  store.updateCatalogue(obj.targetType).then(res => {
    loading.value = false
    catalogueList.value = res
    activeMenu.value = obj.targetType + ''
  }).catch(err => {
    ElMessage(err)
  })
})

onMounted(() => {
  loading.value = true
  store.getCatalogue(activeMenu.value).then(res => {
    loading.value = false
    catalogueList.value = res
  }).catch(err => {
    ElMessage(err)
  })

})

onBeforeUnmount(() => {
  eventBus.off("updateCatalogueBus")
  eventBus.off("moveDirectoryBus")
})

const enterPreview = (docId, type) => {
  if (docId) {
    store.spaceDocId = docId
    const to = router.resolve({name: 'DetailPreview', params: {docId: docId, type: type}})
    window.open(to.href, "_blank")
  }
}

onMounted(() => {
  getDirectoryType()
})


</script>
<style scoped lang="scss">
.dragClass {
  margin: 0 !important;
  height: 0 !important;

  :deep(.el-collapse-item__header) {
    height: 0 !important;
    margin: 0 !important;
  }
}

.el-collapse {
  border-bottom: none;
}

.catalogue-menu {
  position: fixed;
  --el-menu-active-color: #00A298;
  max-width: 3%;
  flex: 0 0 2%;
}

.middle-divider {
  max-width: 1%;
  flex: 0 0 1%;
  height: 366px;
  margin-left: 3%;
  position: fixed;
}

.collapse-content {
  padding-left: 5rem;
  max-width: 100%;
  flex: 0 0 97%;
}

:deep(.el-collapse-item__header) {
  position: relative;
  padding-left: 3rem;
  border-bottom: none;
  height: 4.8rem;
}

:deep(.el-collapse-item__header:hover) {
  background: #F3F6FC;
  border-radius: 6px;
}

:deep(.el-collapse-item__header:hover .one-file-or-dir) {
  display: none;
}

:deep(.el-collapse-item__header:hover .one-file-or-dir-hover) {
  display: flex;
}

.file:hover {
  background: var(--el-tree-node-hover-bg-color);
  cursor: pointer;
}

:deep(.file:hover .one-file-or-dir) {
  display: none;
  color: red;
}

:deep(.file:hover .one-file-or-dir-hover) {
  display: flex;
}

:deep(.el-collapse-item__arrow) {
  position: absolute;
  left: 0;
}

.document-catalogue-wrap {
  min-height: 100%;
}

.document-catalogue-wrap :deep(.el-collapse-item__wrap) {
  border: none;
  margin-left: 4.9rem;
}

:deep(.el-collapse-item:last-child) {
  margin-bottom: unset;
}

.first-level:last-child {
  margin-bottom: 2rem !important;
}

.no-child :deep(.el-collapse-item__arrow) {
  display: none;
}

.enter-button {
  z-index: 99;
  padding-left: 100px;
  padding-right: 100px;
  position: absolute;
  height: 4rem;
}

:deep(.el-collapse-item__content) {
  padding-bottom: 0;
}

.file {
  display: flex;
  align-items: center;
  height: 4.8rem;
  width: 100% !important;
}

.file:hover {
  border-radius: 6px;
}

.file:before {
  content: "  ";
  white-space: pre;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}

> > > .el-affix {
  width: 100% !important;
}

> > > .el-affix--fixed {
  top: calc(100px + 21.2rem) !important;
  z-index: 100 !important;
  position: fixed;
}

> > > .el-menu-item span {
  font-size: 1.6rem;
}

.loading-wrap {
  height: 50vh;
}

.button-font {
  font-size: 1.2rem;
  white-space: normal;
}

.catalogue-button:hover {
  color: #00A298 !important;
}

.catalogue-button-wrap {
  width: 12.5%;
}

.catalogue-button {
  transition: unset !important;
  height: 108px;
  width: 25px;
  background: var(--el-color-info-light-9);
  border-radius: 0;
  margin-left: 0;
  align-items: center;
  justify-content: center;
  border: 1px solid #E0E2E4;
  border-bottom: 0;
  border-top: 0;
}

.button-icon {
  font-size: 17px !important;
  margin-bottom: 0.5rem;
}

.button-icon:hover {
  color: #1A9B92;
}

.catalogue-button-hover {
  color: #00A298 !important;
  border: 1px solid #E0E2E4;
  border-radius: 0;
  background: var(--el-bg-color);
  border-right: 0;
}

:deep(.el-collapse-item__header.is-active ) {
  border-radius: 6px;
  animation-name: fadenum;
  animation-duration: 1.5s;
}

@keyframes fadenum {
  0% {
    background: #e8ecee;
  }
  25% {
    background: #edf1f3;
  }
  50% {
    background: #f1f5f8;
  }
  50% {
    background: #f3f7fa;
  }
  100% {
    background-color: white;
  }
}

:deep(.catalogue-button > span) {
  justify-content: center;
  flex-direction: column;
}

.el-button:hover {
  border-color: #DFEFEC !important;
}

.dropInner {
  display: none;
}

:deep(.el-collapse-item__wrap) {
  overflow: inherit;
}

.catalogue-tree {

  :deep(.el-tree-node__label) {
    width: 100%;
  }

  .file {
    height: 4.5rem !important;
  }

  :deep(.el-tree-node__content) {
    height: 4.5rem;
    border-radius: 1rem;
  }

  :deep(.el-space__item) svg {
    width: 2.8rem !important;
    height: 2.8rem !important;
  }

  :deep(.el-tree-node) {
    padding-top: 0.5rem;
  }


  :deep(.el-tree__drop-indicator) {
    height: 2px;
    width: 30rem;
  }

  :deep(.is-drop-inner .el-tree-node__label) {
    border-radius: 1rem;
  }

  :deep(.el-tree-node__expand-icon) {
    font-size: 2rem !important;
  }
}
</style>
